<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 购物车商品数据
const cartItems = ref([])
const selectedItems = ref([])
const couponCode = ref('')
const isCouponValid = ref(false)
const couponDiscount = ref(0)
const showEmptyCart = ref(false)

// 商品库存数据
const productInventory = {
  'SHADOW-SET-001': { name: '《大闹天宫》皮影套装', price: 280, stock: 100, image: '/images/products/shadowplay-set1.jpg' },
  'BOOK-001': { name: '皮影制作入门书籍', price: 68, stock: 50, image: '/images/products/book1.jpg' },
  'DIY-KIT-001': { name: '传统皮影DIY材料包', price: 150, stock: 30, image: '/images/products/diy-kit1.jpg' },
  'SHADOW-FIGURE-001': { name: '孙悟空皮影人物', price: 120, stock: 20, image: '/images/products/figure1.jpg' },
  'SHADOW-FIGURE-002': { name: '唐僧皮影人物', price: 100, stock: 20, image: '/images/products/figure2.jpg' },
  'ACCESSORY-001': { name: '皮影收藏展示框', price: 80, stock: 40, image: '/images/products/frame1.jpg' }
}

// 模拟数据 - 确保购物车不为空
const mockCartData = [
  { id: 'SHADOW-SET-001', quantity: 2 },
  { id: 'BOOK-001', quantity: 1 },
  { id: 'DIY-KIT-001', quantity: 1 }
]

// 优惠券数据
const validCoupons = [
  { code: 'SHADOW10', discount: 10, description: '满200减10元' },
  { code: 'NEWUSER20', discount: 20, description: '新用户立减20元' },
  { code: 'VIP30', discount: 30, description: '会员专享30元优惠' }
]

// 从localStorage加载购物车数据
const loadCartFromStorage = () => {
  const savedCart = localStorage.getItem('shadowplayCart')
  if (savedCart) {
    const parsedCart = JSON.parse(savedCart)
    // 确保有商品数据
    if (parsedCart.length > 0) {
      cartItems.value = parsedCart
    } else {
      // 如果localStorage为空，使用模拟数据
      cartItems.value = mockCartData
      saveCartToStorage()
    }
  } else {
    // 首次访问，使用模拟数据
    cartItems.value = mockCartData
    saveCartToStorage()
  }
}

// 保存购物车数据到localStorage
const saveCartToStorage = () => {
  localStorage.setItem('shadowplayCart', JSON.stringify(cartItems.value))
}

// 添加商品到购物车
const addToCart = (productId, quantity = 1) => {
  const existingItemIndex = cartItems.value.findIndex(item => item.id === productId)
  
  if (existingItemIndex >= 0) {
    const newQuantity = cartItems.value[existingItemIndex].quantity + quantity
    const maxQuantity = productInventory[productId]?.stock || 99
    
    if (newQuantity <= maxQuantity) {
      cartItems.value[existingItemIndex].quantity = newQuantity
    } else {
      alert(`库存不足，最多可购买 ${maxQuantity} 件`)
      cartItems.value[existingItemIndex].quantity = maxQuantity
    }
  } else {
    // 确保产品存在
    if (productInventory[productId]) {
      cartItems.value.push({ id: productId, quantity })
    }
  }
  
  saveCartToStorage()
  updateSelectedItems()
}

// 更新商品数量
const updateQuantity = (productId, newQuantity) => {
  if (newQuantity < 1) newQuantity = 1
  
  const itemIndex = cartItems.value.findIndex(item => item.id === productId)
  if (itemIndex >= 0) {
    const maxQuantity = productInventory[productId]?.stock || 99
    
    if (newQuantity > maxQuantity) {
      alert(`库存不足，最多可购买 ${maxQuantity} 件`)
      cartItems.value[itemIndex].quantity = maxQuantity
    } else {
      cartItems.value[itemIndex].quantity = newQuantity
    }
    
    saveCartToStorage()
  }
}

// 删除商品
const removeItem = (productId) => {
  cartItems.value = cartItems.value.filter(item => item.id !== productId)
  selectedItems.value = selectedItems.value.filter(id => id !== productId)
  saveCartToStorage()
  updateShowEmptyCart()
}

// 清空购物车
const clearCart = () => {
  if (confirm('确定要清空购物车吗？')) {
    cartItems.value = []
    selectedItems.value = []
    saveCartToStorage()
    updateShowEmptyCart()
  }
}

// 全选/取消全选
const toggleSelectAll = () => {
  if (selectedItems.value.length === cartItems.value.length) {
    selectedItems.value = []
  } else {
    selectedItems.value = cartItems.value.map(item => item.id)
  }
}

// 选择单个商品
const toggleSelectItem = (productId) => {
  const index = selectedItems.value.indexOf(productId)
  if (index >= 0) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push(productId)
  }
}

// 更新选中的商品列表
const updateSelectedItems = () => {
  // 过滤掉已删除的商品
  selectedItems.value = selectedItems.value.filter(id => 
    cartItems.value.some(item => item.id === id)
  )
}

// 检查是否全选
const isAllSelected = computed(() => {
  return selectedItems.value.length === cartItems.value.length && cartItems.value.length > 0
})

// 计算选中商品的总价
const selectedTotalPrice = computed(() => {
  return cartItems.value
    .filter(item => selectedItems.value.includes(item.id))
    .reduce((total, item) => {
      const product = productInventory[item.id]
      return total + (product?.price || 0) * item.quantity
    }, 0)
})

// 计算总商品数量
const totalItemsCount = computed(() => {
  return cartItems.value.reduce((count, item) => count + item.quantity, 0)
})

// 计算运费
const shippingFee = computed(() => {
  const subtotal = selectedTotalPrice.value
  return subtotal >= 200 ? 0 : 15
})

// 计算最终应付金额
const finalAmount = computed(() => {
  const subtotal = selectedTotalPrice.value
  const shipping = shippingFee.value
  const discount = isCouponValid.value ? couponDiscount.value : 0
  return Math.max(0, subtotal + shipping - discount)
})

// 应用优惠券
const applyCoupon = () => {
  if (!couponCode.value) {
    alert('请输入优惠券代码')
    return
  }
  
  const coupon = validCoupons.find(c => c.code === couponCode.value.toUpperCase())
  if (coupon) {
    isCouponValid.value = true
    couponDiscount.value = coupon.discount
    alert(`成功应用优惠券：${coupon.description}`)
  } else {
    isCouponValid.value = false
    couponDiscount.value = 0
    alert('无效的优惠券代码')
  }
}

// 继续购物
const continueShopping = () => {
  router.push('/home')
}

// 立即结算
const checkout = () => {
  if (selectedItems.value.length === 0) {
    alert('请选择要结算的商品')
    return
  }
  
  // 保存选中的商品到localStorage以便结算页面使用
  localStorage.setItem('checkoutItems', JSON.stringify(
    cartItems.value.filter(item => selectedItems.value.includes(item.id))
  ))
  localStorage.setItem('checkoutTotal', finalAmount.value.toString())
  
  // 这里可以跳转到结算页面
  alert(`即将结算，总金额：¥${finalAmount.value.toFixed(2)}`)
  
  // 模拟结算后移除已购买的商品
  cartItems.value = cartItems.value.filter(item => !selectedItems.value.includes(item.id))
  selectedItems.value = []
  saveCartToStorage()
  updateShowEmptyCart()
  isCouponValid.value = false
  couponDiscount.value = 0
  couponCode.value = ''
}

// 添加到心愿单
const addToWishlist = (productId) => {
  const wishlist = JSON.parse(localStorage.getItem('shadowplayWishlist') || '[]')
  if (!wishlist.includes(productId)) {
    wishlist.push(productId)
    localStorage.setItem('shadowplayWishlist', JSON.stringify(wishlist))
    alert('已添加到心愿单')
  } else {
    alert('该商品已在心愿单中')
  }
}

// 更新空购物车状态
const updateShowEmptyCart = () => {
  showEmptyCart.value = cartItems.value.length === 0
}

// 初始化
onMounted(() => {
  loadCartFromStorage()
  updateSelectedItems()
  updateShowEmptyCart()
})
</script>

<template>
  <div class="cart-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">🛒 我的购物车 ({{ totalItemsCount }}件商品)</h1>
      </div>
    </div>

    <div class="container cart-content">
      <!-- 空购物车提示 -->
      <div v-if="showEmptyCart" class="empty-cart">
        <div class="empty-cart-icon">🛒</div>
        <h3>购物车空空如也</h3>
        <p>快去挑选心仪的皮影商品吧！</p>
        <button class="btn btn-primary" @click="continueShopping">去购物</button>
      </div>

      <!-- 购物车商品列表 -->
      <div v-else class="cart-main">
        <!-- 商品列表 -->
        <div class="cart-items">
          <div class="cart-header">
            <div class="header-checkbox">
              <input type="checkbox" id="select-all" v-model="isAllSelected" @change="toggleSelectAll">
              <label for="select-all">全选</label>
            </div>
            <div class="header-product">商品信息</div>
            <div class="header-price">单价</div>
            <div class="header-quantity">数量</div>
            <div class="header-actions">操作</div>
          </div>

          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <div class="item-checkbox">
              <input 
                type="checkbox" 
                :id="`select-${item.id}`" 
                :checked="selectedItems.includes(item.id)"
                @change="toggleSelectItem(item.id)"
              >
              <label :for="`select-${item.id}`"></label>
            </div>

            <div class="item-product">
              <div class="product-image">
                <img :src="productInventory[item.id]?.image" :alt="productInventory[item.id]?.name" />
              </div>
              <div class="product-info">
                <div class="product-name">{{ productInventory[item.id]?.name }}</div>
                <div class="product-stock">库存：{{ productInventory[item.id]?.stock }}件</div>
              </div>
            </div>

            <div class="item-price">¥{{ productInventory[item.id]?.price.toFixed(2) }}</div>

            <div class="item-quantity">
              <button 
                class="quantity-btn minus"
                @click="updateQuantity(item.id, item.quantity - 1)"
              >-</button>
              <input 
                type="number" 
                :value="item.quantity" 
                @change="(e) => updateQuantity(item.id, parseInt(e.target.value) || 1)"
                min="1"
                :max="productInventory[item.id]?.stock || 99"
              >
              <button 
                class="quantity-btn plus"
                @click="updateQuantity(item.id, item.quantity + 1)"
              >+</button>
            </div>

            <div class="item-actions">
              <button class="btn-icon" @click="addToWishlist(item.id)" title="添加到心愿单">
                ❤️
              </button>
              <button class="btn-icon delete" @click="removeItem(item.id)" title="删除">
                ❌
              </button>
            </div>
          </div>
        </div>

        <!-- 购物车操作栏 -->
        <div class="cart-operations">
          <div class="operations-left">
            <button class="btn-outline" @click="clearCart">清空购物车</button>
            <div class="stock-warning" v-if="cartItems.some(item => item.quantity >= productInventory[item.id]?.stock * 0.8)">
              ⚠️ 部分商品库存紧张，请尽快下单
            </div>
          </div>
          <div class="operations-right">
            <span class="selected-count">已选择 {{ selectedItems.length }} 件商品</span>
          </div>
        </div>

        <!-- 订单摘要 -->
        <div class="order-summary">
          <div class="summary-header">
            <h3>订单摘要</h3>
          </div>
          
          <!-- 优惠券 -->
          <div class="coupon-section">
            <label for="coupon">优惠券：</label>
            <input 
              id="coupon"
              v-model="couponCode"
              type="text" 
              placeholder="输入优惠码"
              :disabled="isCouponValid"
            >
            <button class="btn btn-outline" @click="applyCoupon" :disabled="isCouponValid">
              {{ isCouponValid ? '已应用' : '兑换' }}
            </button>
            <span v-if="isCouponValid" class="coupon-success">✓ 已优惠 ¥{{ couponDiscount }}</span>
          </div>

          <div class="summary-details">
            <div class="detail-item">
              <span>小计：</span>
              <span>¥{{ selectedTotalPrice.toFixed(2) }}</span>
            </div>
            <div class="detail-item">
              <span>运费：</span>
              <span>
                ¥{{ shippingFee.toFixed(2) }}
                <span v-if="shippingFee === 0" class="free-shipping">(满200包邮)</span>
              </span>
            </div>
            <div v-if="isCouponValid" class="detail-item discount">
              <span>优惠：</span>
              <span>-¥{{ couponDiscount.toFixed(2) }}</span>
            </div>
          </div>

          <div class="summary-total">
            <span>实付：</span>
            <span class="total-amount">¥{{ finalAmount.toFixed(2) }}</span>
          </div>

          <div class="summary-actions">
            <button class="btn btn-outline" @click="continueShopping">继续购物</button>
            <button class="btn btn-primary" @click="checkout">立即结算</button>
          </div>
        </div>
      </div>

      <!-- 推荐商品 -->
      <div v-if="!showEmptyCart" class="recommendations">
        <h3 class="recommendations-title">🛍️ 为您推荐</h3>
        <div class="recommendations-grid">
          <div v-for="(product, id) in productInventory" :key="id" class="recommendation-card">
            <div class="recommendation-image">
              <img :src="product.image" :alt="product.name" />
            </div>
            <div class="recommendation-info">
              <div class="recommendation-name">{{ product.name }}</div>
              <div class="recommendation-price">¥{{ product.price.toFixed(2) }}</div>
              <button 
                class="btn btn-small btn-primary" 
                @click="addToCart(id, 1)"
                :disabled="product.stock <= 0"
              >
                {{ product.stock > 0 ? '加入购物车' : '已售罄' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 购物车页面容器 */
.cart-container {
  min-height: 100vh;
  background-color: #F5F1E6;
}

/* 页面头部 */
.page-header {
  background-color: #C62F2F;
  color: white;
  padding: 2rem 0;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 2rem;
  margin: 0;
  text-align: center;
}

/* 容器 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

/* 空购物车 */
.empty-cart {
  text-align: center;
  padding: 4rem 2rem;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.empty-cart-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-cart h3 {
  color: #333;
  margin: 0 0 0.5rem 0;
}

.empty-cart p {
  color: #666;
  margin: 0 0 2rem 0;
}

/* 购物车主内容 */
.cart-main {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 2rem;
  margin-bottom: 3rem;
}

/* 购物车商品列表 */
.cart-items {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 购物车头部 */
.cart-header {
  display: grid;
  grid-template-columns: 80px 1fr 100px 150px 80px;
  padding: 1.5rem;
  background-color: #F8F0E3;
  border-bottom: 2px solid #E5D9C5;
  font-weight: bold;
  color: #333;
}

/* 购物车商品项 */
.cart-item {
  display: grid;
  grid-template-columns: 80px 1fr 100px 150px 80px;
  padding: 1.5rem;
  border-bottom: 1px solid #E5D9C5;
  align-items: center;
}

.cart-item:last-child {
  border-bottom: none;
}

/* 商品信息 */
.item-product {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #F5F1E6;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 0.5rem;
}

.product-stock {
  font-size: 0.85rem;
  color: #666;
}

/* 价格 */
.item-price {
  font-weight: bold;
  color: #C62F2F;
  text-align: center;
}

/* 数量控制 */
.item-quantity {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  border: 1px solid #D4AF37;
  background-color: white;
  color: #C62F2F;
  border-radius: 4px;
  font-size: 1.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.quantity-btn:hover {
  background-color: #F5F1E6;
  border-color: #C62F2F;
}

.item-quantity input {
  width: 50px;
  height: 28px;
  border: 1px solid #D4AF37;
  border-radius: 4px;
  text-align: center;
  font-size: 1rem;
}

/* 操作按钮 */
.item-actions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  align-items: center;
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1.2rem;
  padding: 0.25rem;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.btn-icon:hover {
  background-color: #F5F1E6;
}

.btn-icon.delete:hover {
  background-color: #FFF5F5;
}

/* 购物车操作栏 */
.cart-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 0;
  margin-top: -1rem;
}

.operations-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.stock-warning {
  color: #C62F2F;
  font-size: 0.9rem;
}

/* 订单摘要 */
.order-summary {
  background-color: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 2rem;
}

.summary-header h3 {
  margin: 0 0 1.5rem 0;
  color: #333;
  font-size: 1.3rem;
  border-bottom: 2px solid #D4AF37;
  padding-bottom: 0.5rem;
}

/* 优惠券 */
.coupon-section {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
}

.coupon-section label {
  font-weight: 500;
  color: #333;
}

.coupon-section input {
  flex: 1;
  min-width: 150px;
  height: 36px;
  padding: 0 0.75rem;
  border: 1px solid #D4AF37;
  border-radius: 4px;
  font-size: 0.9rem;
}

.coupon-success {
  color: #2D6A4F;
  font-size: 0.9rem;
  white-space: nowrap;
}

/* 摘要详情 */
.summary-details {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-bottom: 1.5rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  color: #666;
}

.detail-item.discount {
  color: #C62F2F;
  font-weight: 500;
}

.free-shipping {
  color: #2D6A4F;
  font-size: 0.85rem;
  margin-left: 0.25rem;
}

/* 总计 */
.summary-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 0;
  margin-bottom: 1.5rem;
  border-top: 1px solid #E5D9C5;
  border-bottom: 1px solid #E5D9C5;
}

.summary-total span:first-child {
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
}

.total-amount {
  font-size: 1.5rem;
  font-weight: bold;
  color: #C62F2F;
}

/* 操作按钮 */
.summary-actions {
  display: flex;
  gap: 1rem;
}

/* 推荐商品 */
.recommendations {
  margin-top: 3rem;
  margin-bottom: 3rem;
}

.recommendations-title {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 1.5rem;
  text-align: center;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.5rem;
}

.recommendation-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.recommendation-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.recommendation-image {
  height: 180px;
  background-color: #F5F1E6;
  overflow: hidden;
}

.recommendation-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.recommendation-card:hover .recommendation-image img {
  transform: scale(1.05);
}

.recommendation-info {
  padding: 1rem;
}

.recommendation-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 0.5rem;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.recommendation-price {
  font-weight: bold;
  color: #C62F2F;
  margin-bottom: 1rem;
}

.btn-small {
  width: 100%;
}

/* 按钮样式 */
.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  outline: none;
}

.btn-primary {
  background-color: #C62F2F;
  color: white;
}

.btn-primary:hover {
  background-color: #8B1A1A;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(198, 47, 47, 0.3);
}

.btn-outline {
  background-color: transparent;
  color: #C62F2F;
  border: 1px solid #C62F2F;
}

.btn-outline:hover {
  background-color: #FFF5F5;
  border-color: #8B1A1A;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .cart-main {
    grid-template-columns: 1fr;
  }
  
  .order-summary {
    position: static;
  }
}

@media (max-width: 768px) {
  .cart-header {
    grid-template-columns: 60px 1fr;
    grid-template-rows: auto auto;
    gap: 0.5rem;
    font-size: 0.9rem;
  }
  
  .header-price,
  .header-quantity,
  .header-actions {
    display: none;
  }
  
  .cart-item {
    grid-template-columns: 60px 1fr;
    grid-template-rows: auto auto;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .item-price,
  .item-quantity,
  .item-actions {
    grid-column: 2;
  }
  
  .item-price {
    font-size: 1.1rem;
    text-align: left;
  }
  
  .item-actions {
    flex-direction: row;
    justify-content: flex-start;
    margin-top: 0.5rem;
  }
  
  .coupon-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .summary-actions {
    flex-direction: column;
  }
  
  .recommendations-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  
  .cart-operations {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }
  
  .cart-item {
    padding: 1rem;
  }
  
  .product-image {
    width: 60px;
    height: 60px;
  }
  
  .total-amount {
    font-size: 1.3rem;
  }
}
</style>